package cn.template.serve_project.aop;

import cn.template.serve_project.aop.note.Authentication;
import cn.template.serve_project.constant.JwtConstant;
import cn.template.serve_project.entity.Permissions;
import cn.template.serve_project.enums.CommonStateEnum;
import cn.template.serve_project.enums.R;
import cn.template.serve_project.exception.BusinessException;
import cn.template.serve_project.service.PermissionsService;
import cn.template.serve_project.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 权限校验Aop
 */
@Component
@Aspect
public class AuthenticationAop {

    @Resource
    PermissionsService tbPermissionsService;

    @Around("@annotation(authentication)")
    public Object permissions(ProceedingJoinPoint point, Authentication authentication) throws Throwable {

        //权限值是否为空
        if (!authentication.path().equals("")) {
            //权限是否可用
            LambdaQueryWrapper<Permissions> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Permissions::getUrl, authentication.path());
            Permissions data = tbPermissionsService.getOne(wrapper);
            if (Objects.isNull(data) || data.getState().equals(CommonStateEnum.error.code)) {
                throw new BusinessException(R.ERROR_PERMISSION);
            }
        }


        //角色是否匹配,或权限级高
        Map<String, Object> userLoginInfo = HttpUtil.getUserLoginInfo();
        Object role = userLoginInfo.get("role");
        if (Objects.nonNull(role) && Objects.nonNull(authentication.role().value)) {
            if (Long.parseLong(String.valueOf(role)) >= authentication.role().value) {
                return point.proceed();
            }
            throw new BusinessException(R.ERROR_PERMISSION);
        }


        //权限是否匹配
        Object permissionsData = userLoginInfo.get(JwtConstant.PERMISSIONS);
        if (Objects.nonNull(permissionsData) && permissionsData instanceof String) {
            List<String> list = JSON.parseArray((String) permissionsData, String.class);
            List<String> collect = list.stream().filter(s -> s.equals(authentication.path())).collect(Collectors.toList());
            if (collect.size() > 0) {
                return point.proceed();
            }
        }

        throw new BusinessException(R.ERROR_PERMISSION);
    }
}
